package com.sky.course.controller;

import com.sky.course.util.VerifyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
* @Description:    图形验证码处理
* @Author:         Joe
* @CreateDate:     2019/10/29 17:11
*/
@RestController
@RequestMapping(value = "/verify")
@Api(value = "图像验证工具",description = "图像验证工具")
public class VerifyController {

    @ApiOperation(value = "获取图形验证码",notes = "获取图形验证码")
    @RequestMapping(value = "/img",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "macCode", value = "图形name", dataType = "String", paramType = "query", required = true)
    })
    public byte[] getVerify(@RequestParam String macCode, HttpServletRequest request){
        Object[] objects = VerifyUtil.createImage();
        String randomStr = (String) objects[0];
        System.out.println(macCode+"的验证码是："+randomStr);
        //在此处删除session里之前产生的验证码
        HttpSession session=request.getSession();
        session.setAttribute(macCode,randomStr);
        return (byte[]) objects[1];
    }

    @ApiOperation(value = "校验验证码",notes = "校验验证码")
    @RequestMapping(value = "/test",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "macCode", value = "图形name", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "yzm", value = "输入的验证码", dataType = "String", paramType = "query", required = true)
    })
    public boolean getmacCode(@Validated @RequestParam String macCode,@RequestParam String yzm,HttpServletRequest request){
        HttpSession session = request.getSession();
        String selectyzm = session.getAttribute(macCode).toString();
        return selectyzm.equals(yzm);
    }
}
